<?php


namespace App\Helpers;


class HttpClass
{
    public function get($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        return json_decode($this->array_iconv($result), true);
    }

    public function post($url, $data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        return curl_exec($ch);
    }

    /**
     * * 对数据进行编码转换
     * @param array/string $data 数组
     * @param string $output 转换后的编码
     * @return array|bool|false|string|string[]|null
     */
    public function array_iconv($data, $output = 'utf-8') {
        $encode_arr = array('UTF-8','ASCII','GBK','GB2312','BIG5','JIS','eucjp-win','sjis-win','EUC-JP');
        $encoded = mb_detect_encoding($data, $encode_arr);
        if (!is_array($data)) {
            return mb_convert_encoding($data, $output, $encoded);
        }
        else {
            foreach ($data as $key=>$val) {
                $key = $this->array_iconv($key, $output);
                if(is_array($val)) {
                    $data[$key] = $this->array_iconv($val, $output);
                } else {
                    $data[$key] = mb_convert_encoding($data, $output, $encoded);
                }
            }
            return $data;
        }
    }
}
